/*
 * TimerRelay.cpp
 *
 *  Created on: 2012. 10. 22.
 *      Author: dalxx
 */
#include <Arduino.h>
#include "RelayTimer.h"

namespace PLCLib {

RelayTimer::RelayTimer() {
	this->timerList=NULL;
}
RelayTimer::~RelayTimer() {
	this->removeAll();
}


void RelayTimer::init(int num_relay, Relay* relay_list, RelayContainer* relay_container) {
	this->removeAll();
	this->RelayDL::init(num_relay, relay_list, relay_container);
	this->timerList=(TimerDesc*)malloc(this->numRelay*sizeof(TimerDesc));

}

void RelayTimer::removeAll() {
	free(this->timerList);
	this->timerList=NULL;
	this->RelayDL::removeAll();
}


void RelayTimer::calculateNext() {
	int i;
	this->RelayDL::calculateNext();

	for(i=0;i<this->numRelay;i++)
	{

		if(this->timerList[i].isExcited)
		{
			unsigned int timediff=millis()-this->timerList[i].start;
			if(this->DLList[i].nextStatus)
			{
				if(timediff<this->timerList[i].delay||timediff>this->timerList[i].delay+this->timerList[i].duration)
				{
					this->DLList[i].nextStatus=false;
				}
			}
			else
				this->timerList[i].isExcited=false;
		}
		else
		{
			if(this->DLList[i].nextStatus)
			{
				this->timerList[i].isExcited=true;
				this->timerList[i].start=millis();
				this->DLList[i].nextStatus=false;
			}
		}
	}
}


void RelayTimer::setRelay(int index, char* logic,int size, unsigned int delay,
		unsigned int duration) {
	this->RelayDL::setRelay(index, logic, size);
	this->timerList[index].delay=delay;
	this->timerList[index].duration=duration;

}




} /* namespace PLCLib */


